import {
  Platform,
} from 'react-native';
import CodePush from "react-native-code-push";

import { GLOBAL } from '../../config/global';
import { ENVIRONMENT } from '../../config/env';
import CODEPUSH_KEYS from '../../../codepush.json';
import Toast from 'react-native-root-toast';

const { deploymentKey } = CODEPUSH_KEYS[ENVIRONMENT[GLOBAL.CURR_ENV].codepushType][Platform.OS];

class HotUpdate {

  static checkingUpdate = false;
  static checkUpdate = async () => {
    return new Promise(resolve => {
      if (!deploymentKey) {
        Toast.show('缺失热更新key,请联系管理员', {
          duration: 1000,
          position: Toast.positions.CENTER,
        });
        resolve({})
      } else if (GLOBAL.IS_EMULATOR || HotUpdate.checkingUpdate) {
        resolve({})
      } else {
        HotUpdate.checkingUpdate = true;
        CodePush.checkForUpdate(deploymentKey).then(update => {
          HotUpdate.checkingUpdate = false;
          resolve({ update })
        }).catch(err => {
          HotUpdate.checkingUpdate = false;
          resolve({ err });
        })
      }
    })
  }

  static getCurrentPackage() {
    return CodePush.getUpdateMetadata(CodePush.UpdateState.RUNNING)
  }

  static doUpdate(downloadProgressCallback) {
    return new Promise(resolve => {
      CodePush.disallowRestart();
      CodePush.sync(
        {
          deploymentKey: deploymentKey
        },
        this.codePushStatus,
        downloadProgressCallback
      ).then(syncStatus => {
        resolve({ syncStatus });
      }).catch(err => {
        resolve({});
        Toast.show('更新失败,检查网络是否畅通,然后重启重试', {
          duration: 1000,
          position: Toast.positions.CENTER,
        });
      });
    })
  }


  static codePushStatus(status) {
    switch (status) {
      case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
        console.log("Checking for update. 检查更新");
        break;
      case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
        console.log("Downloading package. 下载包中");
        break;
      case CodePush.SyncStatus.AWAITING_USER_ACTION:
        console.log("Awaiting user action. 等待用户操作");
        break;
      case CodePush.SyncStatus.INSTALLING_UPDATE:
        console.log("Installing update. 安装更新");
        break;
      case CodePush.SyncStatus.UP_TO_DATE:
        console.log("App up to date. 应用程序更新");
        break;
      case CodePush.SyncStatus.UPDATE_IGNORED:
        console.log("Update cancelled by user. 用户取消更新");
        break;
      case CodePush.SyncStatus.UPDATE_INSTALLED:
        console.log("Update installed and will be applied on restart. 已安装更新，并将在重启时应用。");
        break;
      case CodePush.SyncStatus.UNKNOWN_ERROR:
        console.log("An unknown error occurred. 发生了未知的错误。")
        break;
    }
  }

  static restart() {
    CodePush.allowRestart()
    CodePush.restartApp();
  }
}
export default HotUpdate;
